const axios = require('axios');
const pluralize = require('pluralize'); // Pluralize and singularize any word.
const { createNodeHelpers } = require('gatsby-node-helpers');

async function sourceNodes(
  { actions, createNodeId, createContentDigest },
  configOptions
) {
  // collectionTypes:  ['post']
  const { apiURL, accessToken, collectionTypes } = configOptions;
  const { createNode } = actions;

  // api : /api/posts
  const types = collectionTypes
    .map((type) => type.toLowerCase())
    .map((type) => pluralize(type));
  console.log(
    '>>> plugin: [gatsby-source-mystrapi] pluralize collectionTypes type to types :',
    types
  );

  // 从外部数据源中获取数据
  // { posts: { data: [ { id, attributes: { title, data, content } }[, ...] ], meta: { pagination: { page, pageSize, pageCount, total } } } }
  const final = await getContents(types, apiURL, accessToken);
  // console.log(
  //   '>>> plugin: [gatsby-source-mystrapi] getContents :',
  //   JSON.stringify(final, null, 2)
  // );

  for (const [key, value] of Object.entries(final)) {
    // 1. 构建数据节点对象 allPostsContent
    const { createNodeFactory } = createNodeHelpers({
      typePrefix: key,
      createNodeId,
      createContentDigest,
    });
    const createNodeObject = createNodeFactory('content');

    // 2. 根据数据节点对象创建节点
    value.data.forEach((item) => {
      // 数据节点对象
      const nodeObj = createNodeObject(item);
      // 创建节点
      createNode(nodeObj);
    });
  }
}

async function getContents(types, apiURL, accessToken) {
  const size = types.length;
  let index = 0;
  const final = {};

  // 初始调用
  await loadContents();

  async function loadContents() {
    if (index === size) {
      return;
    }

    const { data } = await axios.get(`${apiURL}/api/${types[index]}`, {
      headers: {
        Authorization: `bearer ${accessToken}`,
      },
    });
    final[types[index++]] = data;

    // 递归调用
    await loadContents();
  }

  return final;
}

module.exports = { sourceNodes };
